import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, Input, message, Popover, Row, Select, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import DeliveryReceiptDetail from '../../components/logisticsOrder/deliveryReceiptDetail';

const FormItem = Form.Item;
const R = require("ramda");

const deliveryReceipt = Form.create()(class DeliveryReceipt extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bookingId: undefined,        //当前订舱ID
            nullifyMemo: undefined,      //当前申请作废的备注
        }
    }

    componentDidMount() {
        this.props.dispatch({ type: 'quickBooking/getListForPage', payload: { ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE), noDraft: true } });
        this.props.dispatch({ type: 'quickBooking/getUserQuickBooking', payload: { status: "2" } });
    }

    changeMemo = (e) => {
        this.setState({ nullifyMemo: e.target.value })
    }

    openMemo = (bookingId) => {
        this.setState({ bookingId, nullifyMemo: undefined });
    }

    closeMemo = () => {
        this.setState({ bookingId: undefined, nullifyMemo: undefined });
    }

    confirmNullify = () => {
        if (!this.state.nullifyMemo) {
            message.error("申请备注不能为空"); return;
        }
        this.props.dispatch({
            type: 'quickBooking/updateQuickBooking',
            payload: {
                id: this.state.bookingId,
                scrapReason: this.state.nullifyMemo,
                status: "3",
                onSuccess: () => {
                    this.closeMemo();
                    this.handleSearch();
                    this.props.dispatch({
                        type: 'quickBooking/getUserQuickBooking',
                        payload: { status: "2" }
                    })
                }
            }
        })
    }
    handleChange = (record, disabled, isBooking, value) => {
        let quickBookingId = null;
        if (value == "2") {
            if (isBooking) {
                if(record.channel == 'website'){
                    quickBookingId = record.id;
                    this.props.dispatch({ type: 'quickBooking/getById', payload: { id: record.id } });
                    this.deliveryReceiptDetail.handleOpen(disabled, null, value, null, null, isBooking, quickBookingId, false, false, false, "3" );
                }else {
                    quickBookingId = record.id;
                    this.props.dispatch({ type: 'quickBooking/getById', payload: { id: record.id } });
                    this.deliveryReceiptDetail.handleOpen(disabled, null, value, null, null, isBooking, quickBookingId, false, false, false, "2" );
                }
            }
            else{
                if (!R.isEmpty(this.props.quickBooking.flag)) {
                    message.error("您有快速订舱单暂未处理，请优先填写对应交接单！");
                    return;
                }
                this.deliveryReceiptDetail.handleOpen(disabled, null, value, null, null, isBooking, quickBookingId, false, false, false, "1");
            }
        }
    }

        handleSearch = flag => {
            let newPage = R.pick(['page', 'size'], this.props.quickBooking.page);
            if (flag) newPage.page = 1;
            this.props.dispatch({
                type: 'quickBooking/getListForPage',
                payload: {
                    ...this.props.form.getFieldsValue(),
                    noDraft: true,
                    ...newPage
                }
            });
        };

        columns = [
            { title: '订舱流水号', dataIndex: 'seqNo', key: 'seqNo' },
            { title: '客户名称', dataIndex: 'cstName', key: 'cstName' },
            // {
            //     title: '服务类型', render(record) {
            //         if (record.serviceItem == '1') {
            //             return '海运整柜';
            //         } else if (record.serviceItem == '2') {
            //             return '海运散货';
            //         } else if (record.serviceItem == '3') {
            //             return '空运';
            //         } else {
            //             return '未知';
            //         }
            //     }
            // },
            { title: '服务类型', dataIndex: 'serviceItemValue', key: 'serviceItemValue'},
            { title: '起运港', dataIndex: 'loadingName', key: 'loadingName' },
            { title: '目的港', dataIndex: 'destinationName', key: 'destinationName' },
            { title: '订舱申请时间', dataIndex: 'createtime', key: 'createtime' },
            {
                title: '渠道来源', render(record) {
                if (record.channel == 'PC') {
                    return '电脑';
                } else if (record.channel == 'website') {
                    return '官网在线订舱';
                } else if (record.channel == 'mobile') {
                    return '手机端';
                }
            }
            },
            {
                title: '状态', render(record) {
                    if (record.status == '1') {
                        return '草稿';
                    } else if (record.status == '2') {
                        return '待处理';
                    } else if (record.status == '3') {
                        return '作废审批中';
                    } else if (record.status == '4') {
                        return '确认作废';
                    } else if (record.status == '5') {
                        return '仲裁作废';
                    } else if (record.status == '6') {
                        return '已处理';
                    } else {
                        return '未知';
                    }
                }
            },
            {
                title: '仲裁原因', dataIndex: 'approvalMemo', key: 'approvalMemo'
            },
            {
                title: '操作',
                render: (record) => {
                    let editLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_BOOKING_ADD} split={true}><a href="#" onClick={this.handleChange.bind(this, record, false, true, "2")}>立即处理</a></RightBox>
                    let voidLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_BOOKING_NULLIFY}>
                        {/* <a href="#" onClick={this.onVoid.bind(this)}>申请作废</a></RightBox> */}

                    <Popover key={record.id} content={<div><div><Input disabled={false} maxLength="500" value={this.state.nullifyMemo} onChange={this.changeMemo.bind(this)} /></div>
                        <div style={{ marginTop: 3 }}>
                            <span style={{ float: 'right' }}><Button onClick={this.closeMemo.bind(this)}>取消</Button></span>
                            <span style={{ marginLeft: 30 }}><Button onClick={this.confirmNullify.bind(this, record.id)}>确认</Button></span>
                        </div></div>
                    }
                        title='请填写作废备注' trigger="click" visible={this.state.bookingId === record.id} onVisibleChange={this.openMemo.bind(this, record.id)}><a href="#">申请作废</a>
                    </Popover>
                </RightBox>
                return <span>{record.status == "2" ? editLink : null}{record.status == "2" ? voidLink : null}</span>
                }
            }
        ];

        render() {
            let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
            const { getFieldDecorator } = this.props.form;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.quickBooking.page.size,
                current: this.props.quickBooking.page.page,
                total: this.props.quickBooking.page.totalRow,
                showSizeChanger: true,
                onShowSizeChange: (current, size) => {
                    let newPage = R.pick(['page', 'size'], this.props.quickBooking.page);
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'quickBooking/getListForPage',
                        payload: {
                            ...this.props.form.getFieldsValue(),
                            noDraft: true,
                           ...newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = R.pick(['page', 'size'], this.props.quickBooking.page);
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'quickBooking/getListForPage',
                        payload: {
                            ...this.props.form.getFieldsValue(),
                            noDraft: true,
                            ...newPage
                        }
                    });
                }
            }

            return (
                <div>
                    <Row>
                        <Col span={8}>
                            <FormItem {...formItemLayout} label={'订舱流水号'}>
                                {getFieldDecorator('seqNo')
                                    (
                                    <Input/>
                                    )
                                }
                            </FormItem>
                        </Col>
                        <Col span={8}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input />)}</FormItem></Col>

                        {/* <Col span={5}>
                            <FormItem {...formItemLayout} label={'报价记录'}>
                                {getFieldDecorator('transportType')
                                    (
                                    <Select style={{ width: "100%" }} allowClear>
                                        <Select.Option value="1">海运整柜</Select.Option>
                                        <Select.Option value="2">海运拼柜</Select.Option>
                                        <Select.Option value="3">空运</Select.Option>
                                        <Select.Option value="4">快递</Select.Option>
                                    </Select>
                                    )}
                            </FormItem>
                        </Col> */}

                        <Col span={7} style={{ marginLeft: 24 }}>
                            <Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleChange.bind(this, null, false, false, "2")} size={'default'}>新增交接单</Button>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)} size={'default'}>查询</Button>
                        </Col>
                    </Row>

                    <Table loading={this.props.loading} rowKey='id' dataSource={this.props.quickBooking.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination}
                        title={() => <span style={{ color: 'red' }}>未处理订仓信息</span>} />
                    <DeliveryReceiptDetail wrappedComponentRef={(inst) => this.deliveryReceiptDetail = inst} refreshList={this.handleSearch} />
                </div>
            );
        }
    })

function mapStateToProps(state) {
    return {
        loading: state.loading.models.deliveryReceipt, deliveryReceipt: state.deliveryReceipt, quickBooking: state.quickBooking
    };
}

export default connect(mapStateToProps)(deliveryReceipt);
